package git_cmd

import (
	"fmt"
	"os"
	"os/exec"

	"atomgit.com/openlinksaas/gitwrap/utils"
	"github.com/spf13/cobra"
)

var pushFlagAuthType string
var pushFlagUser string
var pushFlagPassword string
var pushFlagSshKey string

var _PushGit = &cobra.Command{
	Use: "push",
	Run: func(cmd *cobra.Command, args []string) {
		if len(args) != 2 {
			utils.OutputError(fmt.Errorf("need param [remote name] [branch]"))
			return
		}

		remoteName := args[0]
		branch := args[1]

		cmdPath, err := exec.LookPath("git")
		if err != nil {
			utils.OutputError(err)
			return
		}

		var gitCmd *exec.Cmd
		if pushFlagAuthType == string(AUTH_TYPE_NONE) {
			gitCmd = exec.Command(cmdPath, "push", "--tags", "--progress", remoteName, branch)
		} else if pushFlagAuthType == string(AUTH_TYPE_SSH_KEY) {
			gitCmd = exec.Command(cmdPath, "push", "--tags", "--progress", remoteName, branch)
			gitCmd.Env = []string{}
			gitCmd.Env = append(gitCmd.Env, os.Environ()...)
			gitCmd.Env = append(gitCmd.Env, fmt.Sprintf("GIT_SSH_COMMAND=ssh -i \"%s\"", pushFlagSshKey))
		} else if pushFlagAuthType == string(AUTH_TYPE_PASSWORD) {
			gitCmd = exec.Command(cmdPath, "push", "--tags", "--progress",
				"-c", utils.Quote(fmt.Sprintf("user.name=%s", pushFlagUser)),
				"-c", utils.Quote(fmt.Sprintf("user.password=%s", pushFlagPassword)),
				remoteName, branch)
		}
		if gitCmd == nil {
			utils.OutputError(fmt.Errorf("wrong authType"))
			return
		}

		gitCmd.Dir = gitFlagLocalPath

		logReader, err := gitCmd.StderrPipe()
		if err != nil {
			utils.OutputError(err)
			return
		}
		err = gitCmd.Start()
		if err != nil {
			utils.OutputError(err)
			return
		}
		go processCloneLog(logReader)
		err = gitCmd.Wait()
		if err != nil {
			utils.OutputError(err)
			return
		}
		return
	},
}

func init() {
	_PushGit.Flags().StringVar(&pushFlagAuthType, "authType", "none", "set git push auth type.values are none,sshKey,password")
	_PushGit.Flags().StringVar(&pushFlagUser, "user", "", "set git push user")
	_PushGit.Flags().StringVar(&pushFlagPassword, "password", "", "set git push password")
	_PushGit.Flags().StringVar(&pushFlagSshKey, "sshKey", "", "set git push ssh key")
}
